package com.dianxun.exam.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.dianxun.exam.MainApplication;
import com.dianxun.exam.R;
import com.dianxun.exam.common.AppConfig;
import com.dianxun.exam.common.base.BaseActivity;
import com.dianxun.exam.entity.AnswerBeanDao;
import com.dianxun.exam.entity.BatchEntity;
import com.dianxun.exam.entity.DaoSession;
import com.dianxun.exam.entity.PaperEntity;
import com.dianxun.exam.entity.SubjectInfo;
import com.dianxun.exam.entity.TempSaveBeanDao;
import com.dianxun.exam.entity.TikuBean;
import com.dianxun.exam.entity.TikuBeanDao;
import com.dianxun.exam.entity.TikuSubjectChoiceItemListBeanDao;
import com.dianxun.exam.entity.TikuSubjectChoiceListBeanDao;
import com.dianxun.exam.entity.TikuSubjectJudgmentListBeanDao;
import com.dianxun.exam.entity.UserListBeanDao;
import com.dianxun.exam.net.CallServer;
import com.dianxun.exam.net.DownListener;
import com.dianxun.exam.net.DownloadServer;
import com.dianxun.exam.net.HttpListener;
import com.dianxun.exam.ui.widget.WaitDialog;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;

import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 下载试卷
 */
public class DownloadActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.tv_back)
    TextView tv_back;
    @BindView(R.id.progressbar)
    ProgressBar progressbar;
    @BindView(R.id.layout_paper)
    RelativeLayout layout_paper;
    @BindView(R.id.list_paper)
    RecyclerView list_paper;
    @BindView(R.id.tv_progress)
    TextView tv_progress;
    @BindView(R.id.btn_download)
    Button btn_download;
    @BindView(R.id.btn_ret)
    Button btn_ret;
    @BindView(R.id.layout_wait)
    LinearLayout layout_wait;
    private DaoSession daoSession;
    private AnswerBeanDao answerBeanDao;
    private UserListBeanDao userListBeanDao;
    private TikuBeanDao tikuBeanDao;
    private TikuSubjectJudgmentListBeanDao tikuSubjectJudgmentListBeanDao;
    private TikuSubjectChoiceListBeanDao tikuSubjectChoiceListBeanDao;
    private TikuSubjectChoiceItemListBeanDao tikuSubjectChoiceItemListBeanDao;
    private TempSaveBeanDao tempSaveBeanDao;
    private PaperEntity paperEntity;
    private PaperAdapter paperAdapter;
    private WaitDialog mWaitDialog;

    @Override
    protected int getContentView() {
        return R.layout.activity_download;
    }

    @Override
    protected void initView() {
        daoSession = ((MainApplication) getApplication()).getDaoSession();
        answerBeanDao = daoSession.getAnswerBeanDao();
        userListBeanDao = daoSession.getUserListBeanDao();
        tikuBeanDao = daoSession.getTikuBeanDao();
        tikuSubjectJudgmentListBeanDao = daoSession.getTikuSubjectJudgmentListBeanDao();
        tikuSubjectChoiceListBeanDao = daoSession.getTikuSubjectChoiceListBeanDao();
        tikuSubjectChoiceItemListBeanDao = daoSession.getTikuSubjectChoiceItemListBeanDao();
        tempSaveBeanDao = daoSession.getTempSaveBeanDao();

        mWaitDialog = new WaitDialog(self);
        mWaitDialog.setMessage("保存试卷中，请稍等。。。");
        mWaitDialog.setCancelable(false);
        list_paper.setLayoutManager(new LinearLayoutManager(self));
        paperAdapter = new PaperAdapter();
        list_paper.setAdapter(paperAdapter);

//        int versionNo = AppConfig.getInstance().getVersionNo();
        DownloadServer.getInstance().download(self, CallServer.FILE_URL, new HttpListener<String>() {
            @Override
            public void onSucceed(String response) {
                tv_progress.setVisibility(View.GONE);
                try {
                    JsonReader reader = new JsonReader(new FileReader(response));
                    Gson gson = new Gson();
                    paperEntity = gson.fromJson(reader, PaperEntity.class);
                    List<BatchEntity> datas = new ArrayList<>();
                    for (TikuBean tikuBean : paperEntity.getTikuList()) {
                        BatchEntity batchEntity = new BatchEntity();
                        batchEntity.setBatchNo(tikuBean.getBatchNo());
                        batchEntity.setBatchName(tikuBean.getBatchName());
                        datas.add(batchEntity);
                    }
                    for (int i = 0; i < datas.size() - 1; i++) {
                        for (int j = datas.size() - 1; j > i; j--) {
                            if (datas.get(j).getBatchNo().equals(datas.get(i).getBatchNo())) {
                                datas.remove(j);
                            }
                        }
                    }
                    paperAdapter.setNewData(new ArrayList<>(datas));
                    layout_wait.setVisibility(View.GONE);
                    layout_paper.setVisibility(View.VISIBLE);
                } catch (Exception e) {
                    toast("读取试卷失败");
                    layout_wait.setVisibility(View.GONE);
                    finish();
                }
            }

            @Override
            public void onFailed() {
                 toast("读取下载失败");
                layout_wait.setVisibility(View.GONE);
            }
        }, new DownListener() {
            @Override
            public void onProgress(int progress, long fileCount, long speed) {
                progressbar.setProgress(progress);
                tv_progress.setVisibility(View.VISIBLE);
                tv_progress.setText(progress + "%");
            }
        });
    }

    @Override
    protected void initListeners() {
        tv_back.setOnClickListener(this);
        btn_download.setOnClickListener(this);
        btn_ret.setOnClickListener(this);
    }

    public class PaperAdapter extends BaseQuickAdapter<BatchEntity, BaseViewHolder> {

        public PaperAdapter() {
            super(R.layout.item_download_layout, null);
        }

        @Override
        protected void convert(BaseViewHolder helper, BatchEntity bacthNo) {
            helper.setText(R.id.tv_batch_no, bacthNo.getBatchNo());
            helper.setText(R.id.tv_batch_name, bacthNo.getBatchName());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.btn_download:
                if (answerBeanDao.queryBuilder().where(AnswerBeanDao.Properties.IsUpload.eq(false)).list().size() > 0) {
                    toast("有未上传的考试，无法下载！");
                    return;
                }

                if (tikuSubjectJudgmentListBeanDao.queryBuilder().list().size() > 0) {
                    new AlertDialog.Builder(self).setTitle("将清空上次试卷数据，是否继续？")
                            .setPositiveButton("是", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (paperEntity.getSubjectInfo().getUpdateFlag() == 0) {
                                        insertDB(false);
                                    } else {
                                        insertDB(true);
                                    }
                                }
                            })
                            .setNegativeButton("否", null).show();
                } else {
                    insertDB(true);
                }
                break;
            case R.id.btn_ret:
                finish();
                break;
        }
    }

    Observer<Object> observer = new Observer<Object>() {

        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(Object value) {

        }

        @Override
        public void onError(Throwable e) {
            if (isFinishing()) {
                return;
            }
            if (mWaitDialog.isShowing()) {
                mWaitDialog.dismiss();
            }
            toast(e.getMessage());
        }

        @Override
        public void onComplete() {
            if (isFinishing()) {
                return;
            }
            if (mWaitDialog.isShowing()) {
                mWaitDialog.dismiss();
            }
            toast("下载成功");
            finish();
        }
    };

    private void insertDB(final boolean isDelSubjectInfo) {
        if (!mWaitDialog.isShowing()) {
            mWaitDialog.show();
        }
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) {
                try {
                    long start = System.currentTimeMillis();
                    answerBeanDao.deleteAll();
                    tempSaveBeanDao.deleteAll();
                    userListBeanDao.deleteAll();
                    userListBeanDao.insertInTx(paperEntity.getUserList());
                    tikuBeanDao.deleteAll();
                    tikuBeanDao.insertInTx(paperEntity.getTikuList());
                    SubjectInfo subjectInfo = paperEntity.getSubjectInfo();
                    if (isDelSubjectInfo) {
                        tikuSubjectJudgmentListBeanDao.deleteAll();
                        tikuSubjectJudgmentListBeanDao.insertInTx(subjectInfo.getJudgmentList());
                        tikuSubjectChoiceListBeanDao.deleteAll();
                        tikuSubjectChoiceListBeanDao.insertInTx(subjectInfo.getChoiceList());
                        tikuSubjectChoiceItemListBeanDao.deleteAll();
                        tikuSubjectChoiceItemListBeanDao.insertInTx(subjectInfo.getChoiceItemList());
                    }
                    AppConfig.getInstance().setVersionNo(subjectInfo.getVersionNo());
                    Log.e("插入数据时间：", (System.currentTimeMillis() - start) + "");
                    emitter.onComplete();
                } catch (Exception e) {
                    emitter.onError(e);
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }
}
